import { BaseConnection } from "tsrpc";
import { ClientAction, ClientInfo, Message } from "../shared/api_bot/IMassage";
import component from "../core/tool/component";
import { BaseMessage } from "../shared/api_bot/base";
import { ClientService } from "../service/ClientService";

interface _MsgMessage extends BaseMessage {
    action: ClientAction,
    info?: any,
    data?: any
}

/**
 * 客户端组件 - 主要负责UI交互和连接管理
 * 职责：
 * 1. 管理客户端连接状态
 * 2. 处理消息收发
 * 3. 维护活跃时间
 */
export default class client_component extends component {
    clientInfo!: ClientInfo;
    message!: Message;
    lastActiveTime: number = Date.now();
    
    constructor() {
        super();
    }
    
    init() {
        this.lastActiveTime = ClientService.updateActiveTime();
    }
    
    /**
     * 更新客户端信息
     * @param data 客户端信息
     */
    update_client(data: ClientInfo) {
        this.clientInfo = data;
    }
    
    /**
     * 更新消息信息
     * @param data 消息数据
     */
    update_message(data: Message) {
        this.lastActiveTime = ClientService.updateActiveTime();
        this.message = data;
    }
    
    /**
     * 发送消息
     * @param msg 消息对象
     */
    sendMsg(msg: _MsgMessage) {
        const success = ClientService.sendMessage(
            this.clientInfo,
            this.message,
            msg.action,
            msg.data,
            msg.info
        );
        
        if (!success) {
            console.warn('消息发送失败');
        }
    }
    
    /**
     * 发送文本消息
     * @param text 文本内容
     */
    client_text(text: string) {
        const success = ClientService.sendTextMessage(
            this.clientInfo,
            this.message,
            text
        );
        
        if (!success) {
            console.warn('文本消息发送失败');
        }
    }
    
    /**
     * 发送图片消息
     * @param name 图片名称
     * @param data 图片数据
     */
    client_img(name: string, data: any) {
        const success = ClientService.sendImageMessage(
            this.clientInfo,
            this.message,
            name,
            data
        );
        
        if (!success) {
            console.warn('图片消息发送失败');
        }
    }
    
    /**
     * 获取客户端状态
     */
    getClientStatus() {
        return ClientService.getClientStatus(
            this.clientInfo,
            this.message,
            this.lastActiveTime
        );
    }
    
    /**
     * 检查客户端是否活跃
     * @param timeout 超时时间（毫秒）
     * @returns 是否活跃
     */
    isActive(timeout?: number): boolean {
        return ClientService.isClientActive(this.lastActiveTime, timeout);
    }
    
    /**
     * 重置活跃时间
     */
    resetActiveTime(): void {
        this.lastActiveTime = ClientService.updateActiveTime();
    }
}

